<template>
  <div class="cost-list">
    <a-row type="flex" justify="space-between">
      <a-col>
        <a-range-picker
          v-model:value="timeRange"
          :ranges="{
            昨天: [
              moment().add(-1, 'days').startOf('day'),
              moment().add(-1, 'days').endOf('day'),
            ],
            今天: [moment(), moment()],
            本周: [moment().startOf('week'), moment().endOf('week')],
            本月: [moment().startOf('month'), moment().endOf('month')],
            本年: [moment().startOf('year'), moment().endOf('year')],
          }"
          valueFormat="YYYY-MM-DD"
          @change="onTimeRangeChange"
        >
        </a-range-picker>
      </a-col>
      <a-col>
        <a-button
          v-permission="['costContract', 'curd', 'add']"
          type="primary"
          class="ml-10"
          @click="addNewContract"
        >
          <template #icon><PlusOutlined /></template>
          合同
        </a-button>
      </a-col>
    </a-row>
    <a-card style="margin-top: 10px">
      <a-row>
        <a-col :span="6" class="statistic-col">
          <Statistic
            title="租赁合同数量"
            :value="pageData.leaseContractNums"
          ></Statistic>
        </a-col>
        <a-col :span="6" class="statistic-col border-lf">
          <Statistic
            title="物业合同数量"
            :value="pageData.propertyContractNums"
          ></Statistic>
        </a-col>
        <a-col :span="6" class="statistic-col border-lf border-rt">
          <Statistic
            title="支出保证金总额"
            :value="pageData.bondTotal"
            :precision="2"
            suffix="元"
          ></Statistic>
        </a-col>
        <a-col :span="6" class="statistic-col">
          <Statistic :value="pageData.costTotal" :precision="2" suffix="元">
            <template #title>
              <span>预计支出租金/物业费总和</span>
              <text-tip :tips="['不包含托管计租产生的成本租金']" />
            </template>
          </Statistic>
        </a-col>
      </a-row>
    </a-card>
    <!-- 表格 -->
    <a-table
      :dataSource="dataList"
      :columns="columns"
      :loading="tableLoading"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      :scroll="{ x: 'max-content' }"
      class="mt-10 table"
      :customRow="customRow"
      sticky
    >
      <template #title>
        <a-row type="flex" justify="space-between" class="table-header">
          <a-col> 合同列表 </a-col>
          <a-col> </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'proprietor_name'">
          <span
            :class="record.proprietor_id ? 'link' : ''"
            @click.stop="onProprietorClick(record, record.proprietor_id)"
            >{{ text || "--" }}</span
          >
        </template>
        <template v-if="column.key === 'textShow'">
          <span> {{ text || "--" }}</span>
        </template>
        <template v-if="column.key === 'room_number_txt'">
          <span v-if="record.build_bind && record.build_bind.room.length > 0">
            <a
              v-for="room in record.build_bind.room"
              @click.stop="
                roomClick(
                  room,
                  record.build_bind.room,
                  record.build_bind.village.id
                )
              "
              >{{ room.layer_name + "-" + room.room_name
              }}<text v-if="record.build_bind.room.length > 1">, </text>
            </a>
          </span>
          <span v-else>--</span>
        </template>
      </template>

      <!-- 搜索 -->
      <template
        #customFilterDropdown="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
      >
        <div style="padding: 8px">
          <a-input
            ref="searchInput"
            :placeholder="`搜索 ${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block"
            @change="
              (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
            "
            @pressEnter="handleSearch(selectedKeys, confirm, column.key)"
          />
          <a-button
            type="primary"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="handleSearch(selectedKeys, confirm, column.key)"
          >
            搜索
          </a-button>
          <a-button
            size="small"
            style="width: 90px"
            @click="handleReset(clearFilters, confirm)"
          >
            重置
          </a-button>
        </div>
      </template>
      <template #customFilterIcon="{ filtered, column }">
        <template v-if="column.key === 'type'">
          <FilterFilled />
        </template>
        <template v-else>
          <SearchOutlined
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </template>
      </template>
    </a-table>

    <!-- 房间详情 -->
    <RoomDrawer
      :visible="roomDetailVisible"
      @cancel="cancelRoomDetails"
      :maxRoomNumber="maxRoomNumber"
      :detail="roomDetail"
      pageFrom="SpaceManagement"
    />

    <!-- 业主详情 -->
    <CreateProprietor
      :visible="proprietorDetailVisible"
      :id="proprietorId"
      drawerType="view"
      @onClose="proprietorDetailVisible = false"
    />

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="
        () => {
          ownerDetailVisible = false;
        }
      "
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  ref, defineAsyncComponent,
} from "vue";
import { Statistic, notification, Modal } from "ant-design-vue";
import {
  SearchOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  FilterFilled,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter, useRoute } from "vue-router";
import moment from "moment";
import { TextTip } from "bl-common-vue3";
import RoomDrawer from "@/components/village/RoomDrawer.vue";
import CreateProprietor from "@/views/contract/CostContract/modules/CreateProprietor.vue";
import utils from "@/common/utils/utils";
const OwnerDetailDrawer = defineAsyncComponent(() =>
  import("@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue")
);
export default defineComponent({
  name: "CostContract",
  components: {
    CreateProprietor,
    RoomDrawer,
    Statistic,
    SearchOutlined,
    PlusOutlined,
    TextTip,
    FilterFilled,
    OwnerDetailDrawer,
  },

  setup() {
    const $router = useRouter();

    const state = reactive({
      pageData: {},
      dataList: [],
      columns: [],
      page: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      startTime: "",
      endTime: "",
      timeRange: [],

      order: "created_at", //排序字段 默认id
      sort: "desc", //排序规则 默认降序
      filters: {}, //筛选项
      searchData: {}, //搜索项
      timeoutList: [], //状态筛选列表
      statusList: [], //状态筛选列表
      ownerDetailVisible: false,
      ownerId: 0,
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      console.log(filters, sorter);
      if (sorter) {
        if (sorter.order) {
          state.sort = sorter.order == "ascend" ? "asc" : "desc";
        } else {
          state.order = "";
          state.sort = "";
        }
      }
      if (filters) {
        for (let key in filters) {
          if (
            key == "proprietor_name" &&
            filters["proprietor_name"] &&
            filters["proprietor_name"].length > 0
          ) {
            filters["name"] = filters["proprietor_name"][0];
            delete filters["proprietor_name"];
          }
          if (filters[key] && filters[key].length > 0) {
            filters[key] = filters[key][0];
          }
          if (filters[key] && filters[key].length == 0) {
            delete filters[key];
          }
        }

        state.filters = filters;
      }
      getDataList();
    };

    const handleSearch = (selectedKeys, confirm, searchKey) => {
      console.log(selectedKeys);
      confirm();
    };

    const handleReset = (clearFilters, confirm) => {
      clearFilters();
      confirm();
    };

    const columns = computed(() => {
      return [
        {
          title: "业主名称",
          dataIndex: "proprietor_name",
          key: "proprietor_name",
          width: 250,
          customFilterDropdown: true,
        },
        {
          title: "租赁面积",
          dataIndex: "lease_area",
          width: 150,
          customRender: ({ text }) => {
            return text ? text + "㎡" : " - ";
          },
        },
        {
          title: "租期时间",
          width: 250,
          customRender: ({ record }) => {
            return record.lease_starttime && record.lease_endtime
              ? record.lease_starttime + " ~ " + record.lease_endtime
              : "-";
          },
        },
        {
          title: "签订日",
          dataIndex: "sign_time",
          width: 150,
          customRender: ({ text }) => {
            return text ? text : " - ";
          },
        },
        {
          title: "合同类型",
          dataIndex: "type",
          key: "type",
          width: 150,
          customRender: ({ record }) => {
            return record.type_txt ? record.type_txt : " - ";
          },
          filters: [
            {
              text: "租赁合同",
              value: "1",
            },
            {
              text: "物业合同",
              value: "2",
            },
          ],
          filterMultiple: false,
        },
        {
          title: "计租方式",
          dataIndex: "lease_mode_txt",
          width: 200,
        },
        {
          title: "合同编号",
          dataIndex: "contract_number",
          width: 250,
          customFilterDropdown: true,
        },
        {
          title: "楼宇名称",
          dataIndex: "build_name",
          width: 150,
        },
        {
          title: "楼层-房号",
          dataIndex: "room_number_txt",
          key: "room_number_txt",
          width: 150,
        },
        {
          title: "剩余租期",
          dataIndex: "surplus_days",
          width: 150,
          customRender: ({ record }) => {
            return record.surplus_days ? record.surplus_days + "天" : " - ";
          },
        },
        {
          title: "合同状态",
          dataIndex: "status",
          key: "status",
          width: 150,
          customRender: ({ record }) => {
            return record.status_txt ? record.status_txt : " - ";
          },
          filters: [
            {
              text: "正常执行中",
              value: 2,
            },
            {
              text: "已到期",
              value: 16,
            },
          ],
          filterMultiple: false,
        },
      ];
    });

    const getDataList = () => {
      state.tableLoading = true;
      let params = {
        page: state.page,
        limit: state.pageSize,
        sort: state.sort,
        order: state.order,
      };
      if (state.startTime && state.endTime) {
        params.start_time = state.startTime;
        params.end_time = state.endTime;
      }
      if (state.filters) {
        for (let key in state.filters) {
          params[key] = state.filters[key];
        }
      }
      request
        .get("/org", "/contract/contractCost", {
          ...params,
        })
        .then((res) => {
          state.pageData = res;
          state.dataList = res.list;
          state.total = res.total;
        })
        .finally(() => {
          state.tableLoading = false;
        });
    };

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_contract_detail`,
            app: 'org',
            name: `合同详情【${record.proprietor_name}】`,
            url: `/contract/contractDetail?id=${record.id}&noBack=1`,
          }
        })
      }
    };

    const init = () => {
      getDataList();
    };

    init();

    const onTimeRangeChange = (dates, dateStrings) => {
      state.timeRange = dateStrings;
      state.startTime = dateStrings[0];
      state.endTime = dateStrings[1];
      state.page = 1;
      getDataList();
    };

    // 新建合同
    const addNewContract = () => {
      // query: { type: props.type }
      // 验证是否有审批流程
      request.post("/org", "/contract/checkBuildProcess").then((res) => {
        if (res.hasProcess) {
          if (window.__MICRO_APP_ENVIRONMENT__) {
              window.microApp.forceDispatch({
                type: "SetMicroPages",
                microInfo: {
                  microId: `org_add_contract_costContract`,
                  app: 'org',
                  name: `创建合同`,
                  url: `/contract/addContract?contractType=costContract`,
                }
              })
          }
        } else {
          Modal.confirm({
            title: () => "提示",
            content: () => "您需要先添加合同新建审批流程才能创建合同哦~",
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            okText: () => "前往",
            onOk() {
              utils.goProcessContract({type: "add"});
            },
          });
        }
      });
    };

    // 获取最大房源号
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    // 房间点击详情
    const maxRoomNumber = ref(0);
    const roomDetailVisible = ref(false);
    const roomDetail = ref({});
    const roomClick = (room, room_list, village_id) => {
      // console.log(room, layer);
      let roomData = room;
      roomData.village_id = village_id;
      roomDetail.value = roomData;
      maxRoomNumber.value = getMaxRoomNumber(room_list);
      roomDetailVisible.value = true;
    };
    const cancelRoomDetails = () => {
      roomDetailVisible.value = false;
    };

    const proprietorDetailVisible = ref(false);
    const proprietorId = ref(0);

    /** 查看业主 */
    const onProprietorClick = (record, id) => {
      if (id) {
        if (record.is_new == 1) {
          // 新版业主 等于租客
          state.ownerId = id;
          state.ownerDetailVisible = true;
        } else {
          proprietorId.value = id;
          proprietorDetailVisible.value = true;
        }
      }
    };

    return {
      ...toRefs(state),
      pagination,
      handleTableChange,
      moment,
      onTimeRangeChange,
      customRow,
      handleSearch,
      handleReset,
      columns,
      addNewContract,
      roomDetailVisible,
      maxRoomNumber,
      roomDetail,
      roomClick,
      cancelRoomDetails,
      proprietorDetailVisible,
      proprietorId,
      onProprietorClick,
    };
  },
});
</script>

<style lang="less" scoped>
.cost-list {
  padding: 10px;

  :deep(.ant-statistic-title) {
    text-align: center;
  }

  :deep(.ant-statistic-content) {
    text-align: center;
  }

  .border-lf {
    border-left: 1px solid #e9e9e9;
  }

  .border-rt {
    border-right: 1px solid #e9e9e9;
  }

  .table {
    .table-header {
      margin: 0 16px;
      color: rgba(0, 0, 0, 0.8);
    }
  }

  :deep(.room-txt) {
    display: inline-block;
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
